<?php

namespace app\home\controller;

use app\common\controller\Home;

// 引入FastAdmin自带的一个邮箱发送类
use app\common\library\Email;

class Business extends Home
{

    public $NoLogin = [];
    public function __construct(){
        parent::__construct();
        // 在公共区域加载模型
        $this->BusinessModel = model('Business.User');
        $this->CommentModel = model('Subject.Comment');
    }

    // 会员首页
    public function index(){
        
        return $this->view->fetch();
    }

    // 基本资料页
    public function profile(){
        // var_dump($this->business);
        // exit;
        
        if($this->request->isPost()){
            // var_dump($this->request->param());
            // exit;
            $nickname = $this->request->param('nickname','','trim');
            // var_dump($nickname);
            $mobile = $this->request->param('mobile','','trim');
            $email = $this->request->param('email','','trim');
            $gender = $this->request->param('gender','0','trim');
            // var_dump($gender);
            $code = $this->request->param('code','','trim');
            

            $data = [
                'id' => $this->view->business['id'],
                'nickname' => $nickname,
                'mobile' => $mobile,
                'gender' => $gender
            ];
            
            $password = $this->request->param('password','','trim');
            if(!empty($password)){
                $salt = randstr();
                // var_dump($salt);
                $password = md5($password.$salt);
                $data['salt'] = $salt;
                $data['password'] = $password;
            }
            // 判断是否修改了邮箱 输入的邮箱不等于数据库中存入的邮箱
            // 如果邮箱改变，需要重新认证
            if($email != $this->view->business['email']){
                $data['email'] = $email;
                $data['auth'] = '0';
            }

            // 判断是否有地区数据
            if(!empty($code)){
                // 查询省市区的地区码出来
                $parent = model('Region')->where(['code'=>$code])->value('parentpath');

                if(!empty($parent)){
                    $arr = explode(',',$parent);
                    $data['province'] = isset($arr[0]) ? $arr[0] : null;
                    $data['city'] = isset($arr[1]) ? $arr[1] : null;
                    $data['district'] = isset($arr[2]) ? $arr[2] : null;
                }
            }

            // 判断是否有图片上传
            if(isset($_FILES['avatar']) && $_FILES['avatar']['error'] == 0){
                $success = build_upload('avatar');
                // var_dump($success);
                // exit;
                // 如果上传失败，就提醒
                if(!$success['result']){
                    $this->error($success['msg']);
                    exit;
                }

                // 如果上传成功
                $data['avatar'] = $success['data'];
                
            }

            // var_dump($data);
            // exit;

            // 执行更新语句 数据验证->需要用到验证器

            // 更新语句
            // 如果是更新语句，需要给data提供一个主键id的值
            $result = $this->BusinessModel->validate('common/Business/Business.profile')->isUpdate(true)->save($data);

            if($result === FALSE){
                $this->error($this->BusinessModel->getError());
                exit;
            }

            // 判断是否有旧图片，如果有就删除
            if(isset($data['avatar'])){
                $res = is_file(".".$this->view->business['avatar']) && @unlink(".".$this->view->business['avatar']);

            }

            // 修改了手机号，覆盖一下cookie
            if($data['mobile'] != $this->view->business['mobile']){
                $cookie = [
                    'id' => $data['id'],
                    'mobile' => $data['mobile']
                ];

                // 覆盖cookie
                cookie('business',$cookie);
            } 
            
            $this->success('更新资料成功',url('home/business/index'));
            exit;

        }

        return $this->view->fetch();
    }


    // 邮箱验证页
    public function email(){
        // 加载模型
        $EmsModel = model('common/Ems');
        // 是否有ajax请求过来
        if($this->request->isAjax()){
            $action = $this->request->param('action','','trim');
            // var_dump($action);
            // exit;

            if($action == "send"){
                // 获取用户信息
                $email = isset($this->view->business['email']) ? $this->view->business['email'] : '';

                if(empty($email)){
                    $this->error('邮箱地址为空');
                    exit;
                }

                // 生成一个验证码
                $code = randstr(5);
                
                // 开启事务
                $EmsModel->startTrans();

                // 删除掉之前旧的验证码
                $EmsModel->where(['email'=> $email])->delete();

                // 把验证码插入到数据库表中
                $data = [
                    'event' => 'auth',
                    'email' => $email,
                    'code' => $code,
                    'times' => 0
                ];

                // var_dump($data);
                // exit;
                // 插入数据
                $ems = $EmsModel->save($data);

                if($ems === FALSE){
                    $this->error('验证码插入失败');
                    exit;
                }

                // 邮件主题
                $name = config('site.name');
                $subject = "【{$name}】邮箱验证";

                // 组装文字信息
                $message = "<div>感谢您的使用，您的邮箱验证码为：<b>$code</b></div>";

                // 实例化邮箱验证类
                $PhpMailer = new Email;

                // 邮箱发送有规律，不可以发送关键词
                $result = $PhpMailer
                    ->to($email)
                    ->subject($subject)
                    ->message($message)
                    ->send();

                // 检测邮箱发送成功还是失败
                if($result){
                    // 发送验证码成功
                    // 将事务提交，提交的意思是让刚插入的记录真实存在到数据表中
                    $EmsModel->commit();
                    $this->success('邮件发送成功，请注意查收');
                    exit;
                }else{
                    // 将刚才插入成功的验证码记录撤销回滚
                    $EmsModel->rollback();
                    $this->error($PhpMailer->getError());
                    exit;
                }
            }           
        }

        // 是否有post请求过来
        if($this->request->isPost()){
            $code = $this->request->param('code','','trim');
            
            if(empty($code)){
                $this->error('验证码不能为空');
                exit;
            }

            $email = isset($this->view->business['email']) ? trim($this->view->business['email']) : '';

            if(empty($email)){
                $this->error('邮箱不能为空');
                exit;
            }

            // 开启事务
            $EmsModel->startTrans();
            $this->BusinessModel->startTrans();

            // 查询这个验证码是否存在
            $where = ['email'=>$email,'code'=>$code];
            $check = $EmsModel->where($where)->find();

            // var_dump($check->toArray());
            // exit;

            // 如果没有找到记录
            if(!$check){
                $this->error('您输入的验证码有误，请重新输入');
                exit;
            }

            // 1、更新用户表
            // 2、删除验证码记录

            // 组装数据
            $data = [
                'id' => $this->view->business['id'],
                'auth' => '1'
            ];
            
            // 执行更新
            $BusinessStatus = $this->BusinessModel->isUpdate(true)->save($data);

            if($BusinessStatus === FALSE){
                $this->error('用户邮箱认证状态修改失败');
                exit;
            }

            // 删除验证码记录
            $EmsStatus = $EmsModel->where($where)->delete();

            if($EmsStatus === FALSE){
                // 先要将用户表的更新回滚
                $this->BusinessModel->rollback();
                $this->error('验证码记录删除失败');
                exit;
            }

            if($BusinessStatus === FALSE || $EmsStatus === FALSE){
                $EmsModel->rollback();
                $this->BusinessModel->rollback();
                $this->error('验证失败');
                exit;
            }else{
                // 提交事务
                $this->BusinessModel->commit();
                $EmsModel->commit();
                $this->success('邮箱验证成功',url('home/business/index'));
                exit;
            }
        }


        return $this->view->fetch();
    }

    // 订单页
    public function order(){
        // 获取用户id
        $busid = $this->view->business['id'];
        // var_dump($busid);
        // exit;
        $this->assign('busid',$busid);
        // 加载订单模型
        $this->OrderModel = model('Subject.Order');
        
        if($this->request->isAjax()){
            $page = $this->request->param('page',0,'trim');
            $limit = $this->request->param('limit',10,'trim');

            $count = $this->OrderModel->where(['busid'=>$busid])->count();
            // var_dump($count);

            if(!$count){
                $this->error('暂无更多订单');
                exit;
            }

             // 偏移量
             $start = ($page-1)*$limit;
             $list = $this->OrderModel
             ->with('subject')
             ->where('busid',$busid)
             ->order('createtime desc')
             ->limit($start, $limit)
             ->select();

             if($list)
             {
                foreach($list as &$item)
                {
                    $where = [
                        'busid' => $busid,
                        'subid' => $item['subid']
                    ];

                    //查询订单是否有评论
                    $comment = $this->CommentModel->where($where)->find();

                    if($comment)
                    {
                        $item['comment'] = true;
                    }else
                    {
                        $item['comment'] = false;
                    }
                }
             }
             

             $data = [
                 'count' => $count,
                 'list' => $list,
             ];

             if(empty($list)){
                $this->error('暂无更多订单');
                exit;
            }else{
                $this->success('成功返回订单',null,$data);
                exit;
            }

        }


        return $this->view->fetch();
    }

    // 我的消费页
    public function record(){

        $busid = $this->view->business['id'];
        $this->assign('busid',$busid);

        $this->RecordModel = model('Business.Record');

        if($this->request->isAjax()){
            $page = $this->request->param('page',0,'trim');
            $limit = $this->request->param('limit',10,'trim');

            $count = $this->RecordModel->where(['busid'=>$busid])->count();
            // var_dump($count);

            if(!$count){
                $this->error('暂无更多消费记录');
                exit;
            }

             // 偏移量
             $start = ($page-1)*$limit;
             $list = $this->RecordModel
             ->where('busid',$busid)
             ->order('createtime desc')
             ->limit($start, $limit)
             ->select();
            

            //  var_dump(collection($list)->toArray());
            //  exit;
             


             $data = [
                 'count' => $count,
                 'list' => $list,

             ];

            //  var_dump($data);
            //  exit;

             if(empty($list)){
                $this->error('暂无更多消费记录');
                exit;
            }else{
                $this->success('成功返回消费记录',null,$data);
                exit;
            }

        }


        return $this->view->fetch();
    }

    // 评价
    public function comment(){

        $subid = $this->request->param('subid',0,'trim');

        if(!$subid){
            $this->error('该课程不存在');
            exit;
        }

        $this->SubjectModel = model('Subject.Subject');
        $subject = $this->SubjectModel->where('id',$subid)->find();
        $title = $subject['title'];
        $this->assign('title',$title);
        // var_dump($subject['title']);
        // exit;

        if($this->request->isPost()){
            $content = $this->request->param('content','','trim');
            // var_dump($content);
            // exit; 

            if(empty($content)){
                $this->error('请填写评价');
                exit;
            }

            // 组装数据
            $data = [
                'content' => $content,
                'busid' => $this->view->business['id'],
                'subid' => $subid
            ];

            // var_dump($data);
            // exit;

            $result = $this->CommentModel->save($data);

            if($result === FALSE){
                $this->error('评论失败，请重试');
                exit;
            }else{
                $this->success('评论成功',url('home/business/order'));
                exit;
            }
        }
        
        return $this->view->fetch();
    }
}
